package net.es.weathermap.http;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.DefaultServlet;
import org.mortbay.jetty.servlet.ServletHolder;

public class JettyLauncher {
    private Server server;
    private static JettyLauncher instance;
    private int httpPort = 8080;
    private String host = "0.0.0.0";

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public static JettyLauncher getInstance() {
        if (instance == null) {
            instance = new JettyLauncher();
        }
        return instance;
    }

    private JettyLauncher() {
    }

    public void initServer() {
        this.initServer(httpPort, host);
    }

    public void initServer(int port, String host) {
        server = new Server();
        Connector connector=new SocketConnector();
        connector.setPort(port);
        connector.setHost(host);
        server.setConnectors(new Connector[]{connector});

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        server.setHandler(contexts);

        Context root = new Context(server,"/",Context.SESSIONS);
        root.addServlet(new ServletHolder(new DefaultServlet()), "/*");


        // FIXME: change this to a proper path
        root.setResourceBase("./src/main/webapp");
        ServletHolder servletHolder = new ServletHolder(new JSONServlet());
        servletHolder.setName("servlet");
        servletHolder.setForcedPath("servlet");
        root.addServlet(servletHolder, "/servlet/*");


    }

    public Server getServer() {
        return server;
    }

    public int getHttpPort() {
        return httpPort;
    }

    public void setHttpPort(int httpPort) {
        this.httpPort = httpPort;
    }

}
